/*
 * Copyright 2010 Cedric Priscal
 *
 * This file is part of stupid-avr-robot.
 *
 * stupid-avr-robot is free software: you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * stupid-avr-robot is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with stupid-avr-robot.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "AnalogChannel.h"
#include "AnalogToDigitalConverter.h"
#include "Timer/Timer.h"

AnalogChannel::AnalogChannel(CHANNEL channel, VREF vref) {
	mChannel = channel;
	mVref = vref;
	/* Set IO as input, no pull */
	if (channel <= CHANNEL_ADC7) {
		DDRC &= ~_BV(channel);
		PORTC &= ~_BV(channel);
		/* Deactivate digital input buffer for power consumption */
		if (channel <= CHANNEL_ADC5) {
			DIDR0 |= _BV(channel);
		}
	}
}

void AnalogChannel::startOneShot() {
	mMs = mPeriod = 0;
	AnalogToDigitalConverter::getInstance()->startADC(this);
}

void AnalogChannel::startPeriodic(unsigned short period) {
	mMs = mPeriod = period;
	gTimer.schedule(this, 0, gTimer.now() + 1000);
}

void AnalogChannel::stop() {
	mMs = mPeriod = 0;
}

void AnalogChannel::onTimer(char what, unsigned short when) {
	if (mPeriod) {
		/* 1ms has been elapsed */
		mMs--;
		if (!mMs) {
			/* The period has been elapsed,
			 * we can launch a new measure.
			 */
			mMs = mPeriod;
			//gAnalogToDigitalConverter.startADC(this);
			AnalogToDigitalConverter::getInstance()->startADC(this);
		}
		/* Reprogram timer for 1ms from now */
		gTimer.schedule(this, 0, when + 1000);
	}
}
